define(['jquery'], function ($) {

	function UploadImg (opt) {
		
		this.default = {
			elem: $('.add-img'), // 添加图片按钮
			type: '1', // 1 => 单图上传，覆盖之前的图片，2=> 追加
		};
		this.opt = $.extend({}, this.default, opt);
		this.init();
	}

	// 绑定change事件， 选取图片
	UploadImg.prototype.bindEvent = function() {
		var _self = this;
		console.log(_self.opt.elem.length);

		// 为input绑定change事件，当用户选择图片是上传
		_self.opt.elem.find('input').on('change', function (e) {
			var file = e.target.files,
				num = file.length, 
				_this = this; // 点击的input
			$('.loading').removeClass('hide');

			for (let i = 0; i < file.length; i++) {
				if (!_self.beforeUpload(file[i])) continue;

				var reader = new FileReader();
				reader.onload = function (evt) {

					_self.ajaxPost({'imageData':evt.target.result})
						.then(function (json) { 
							_self.appendImg(json, _this);
							num--;
						})
						.catch(function (err) { 
							alert('上传失败');
							num--;
						});

					if (num == 0) $('.loading').addClass('hide');
				}
				reader.readAsDataURL(file[i]); 
			}

		});
	}
	

	/**
	 * 图片上传前验证
	 * @param file=> 单张图片
	 */
	UploadImg.prototype.beforeUpload = function (file) {

		// 盘点押宝
		if (file.type.split('/')[0] != 'image') {
			alert('非图片文件不支持上传');
			return false;
		}

		if (file.size > 300 * 1024){
			alert('为了手机端的浏览体验，请上传小于300k的图片');
			return false;
		}

		return true;
 	}


 	/*
	 * ajax上传文件
	 * @param: data => ajax提交的数据
	 * @return promise对象
	 */
	UploadImg.prototype.ajaxPost = function (data) {

	 	return new Promise(function (resolve, reject) {
	 		$.ajax({
	 			url: '/Api/Upload/ajax_uploadFile',
	 			type: 'post',
	 			datatype: 'json',
	 			data: data,
	 			timeout: 10000,
	 			success: function (json) {
	 				json.code == 0 ? alert(json.msg) : resolve(json);
	 			},
	 			error: function () {
	 				alert('上传失败');
	 				$('.loading').removeClass('hide');
	 			}
	 		})
	 	});
	}


	/**
	 * 只能上传单张图片，上传到图片替换之前的图片
	 * @param： json => 上传成功之后返回的数据 ｛code: , msg: , url: ｝
	 */
	UploadImg.prototype.appendImg = function (json, selector) {

		var elem = $(selector).parents('.add-img'),
			tem = '<div class="upload-img-item">'+
                        '<img src="'+ json.url +'">'+
                        '<span class="del-img">×</span>'+
                        '<input type="hidden" name="" value="'+ json.url +'">'+
                   '</div>';

        if (this.type == 1) {
        	elem.siblings('.upload-img-item').remove();
        	elem.find('span').text('变更');
        }

        elem.before(tem);
	}


	// 初始化上传图片
	UploadImg.prototype.init = function () {

		// 添加上传提示框
		if ($('.loading').length <= 0) { 
			var tem = '<div class="loading hide"><img class="tip" src="/static/img/loading.gif"></div>';
			$('body').append(tem);
		}

		this.bindEvent();
	}

	// 删除图片
	$('.form-group').on('click', '.del-img', function () {
		$(this).parents('.upload-img-item').remove();

		group = $(this).parents('.form-group');
		if (group.find('.upload-img-item').length <= 0) {
			group.find('.add-img span').text('+加图');
		}
	});

	return UploadImg;
})